package com.ruoyi.mp.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.mp.api.domain.MpAccount;
import com.ruoyi.mp.domain.MpKf;
import com.ruoyi.mp.mapper.MpKfMapper;
import com.ruoyi.mp.service.IMpAccountService;
import com.ruoyi.mp.service.IMpKfService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

/**
 * 公众号客服Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-30
 */
@Service
public class MpKfServiceImpl implements IMpKfService 
{
    @Autowired
    private MpKfMapper mpKfMapper;
    @Autowired
    private IMpAccountService iMpAccountService;
    @Autowired
    private WxMpService wxService;

    private static final Logger log = LoggerFactory.getLogger(MpKfServiceImpl.class);
    /**
     * 查询公众号客服
     * 
     * @param id 公众号客服主键
     * @return 公众号客服
     */
    @Override
    public MpKf selectMpKfById(Long id)
    {
        return mpKfMapper.selectMpKfById(id);
    }

    /**
     * 查询公众号客服列表
     * 
     * @param mpKf 公众号客服
     * @return 公众号客服
     */
    @Override
    public List<MpKf> selectMpKfList(MpKf mpKf)
    {
        return mpKfMapper.selectMpKfList(mpKf);
    }

    /**
     * 新增公众号客服
     * 
     * @param mpKf 公众号客服
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMpKf(MpKf mpKf) throws WxErrorException {
        mpKf.setCreateTime(DateUtils.getNowDate());
        try {
            WxMpKfAccountRequest wxMpKfAccountRequest = new WxMpKfAccountRequest(mpKf.getKfAccount(),mpKf.getNickName(),mpKf.getKfWx());
            wxService.switchoverTo(mpKf.getAppId()).getKefuService().kfAccountAdd(wxMpKfAccountRequest);
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        return mpKfMapper.insertMpKf(mpKf);
    }

    /**
     * 绑定客服微信，此微信号为用户微信微信号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int kfInviteWorker(MpKf mpKf) throws WxErrorException {
        try {
            WxMpKfAccountRequest wxMpKfAccountRequest = new WxMpKfAccountRequest(mpKf.getKfAccount(),mpKf.getNickName(),mpKf.getKfWx());
            wxService.switchoverTo(mpKf.getAppId()).getKefuService().kfAccountInviteWorker(wxMpKfAccountRequest);
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        return mpKfMapper.updateMpKf(mpKf);
    }

    /**
     * 更新客服列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int getkflist(Long id) throws WxErrorException {
        try {
            MpAccount mpAccount = this.iMpAccountService.selectMpAccountById(id);
            WxMpKfList wxMpKfList  =    wxService.switchoverTo(mpAccount.getAppId()).getKefuService().kfList();
            mpKfMapper.deleteMpKfByAppId(mpAccount.getAppId());
            return mpKfMapper.updateMpkfList(new MpKf().convert(wxMpKfList,mpAccount));
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }

    }

    /**
     * 修改公众号客服
     * 
     * @param mpKf 公众号客服
     * @return 结果
     */
    @Override
    public int updateMpKf(MpKf mpKf)
    {
        mpKf.setUpdateTime(DateUtils.getNowDate());
        return mpKfMapper.updateMpKf(mpKf);
    }

    /**
     * 批量删除公众号客服
     * 
     * @param ids 需要删除的公众号客服主键
     * @return 结果
     */
    @Override
    public int deleteMpKfByIds(Long[] ids)
    {
        return mpKfMapper.deleteMpKfByIds(ids);
    }

    /**
     * 删除公众号客服信息
     * 
     * @param id 公众号客服主键
     * @return 结果
     */
    @Override
    public int deleteMpKfById(Long id)
    {
        return mpKfMapper.deleteMpKfById(id);
    }

    /*
    * 更新客服信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int kfAccountUpdate(MpKf mpKf) throws WxErrorException {
        try{
            MpAccount mpAccount = this.iMpAccountService.selectMpAccountById(mpKf.getAccountId());
            WxMpKfAccountRequest accountRequest = new WxMpKfAccountRequest(
                    mpKf.getNickName(),
                    mpKf.getKfWx(),
                    mpKf.getKfAccount()+"@"+mpAccount.getAccount()
            );
            wxService.switchoverTo(mpAccount.getAppId()).getKefuService().kfAccountUpdate(accountRequest);
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        return mpKfMapper.updateMpKf(mpKf);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean kfAccountUploadHeadImg(MpKf mpKf) throws WxErrorException {

        try{
            MpAccount mpAccount = this.iMpAccountService.selectMpAccountById(mpKf.getAccountId());
            String kfAccount = mpKf.getKfAccount()+"@"+mpAccount.getAccount();
            File imageFile = new File(mpKf.getKfHeadimgurl());
            wxService.switchoverTo(mpAccount.getAppId()).getKefuService().kfAccountUploadHeadImg(kfAccount,imageFile);
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        return mpKfMapper.updateMpKf(mpKf) != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean kfAccountDel(MpAccount mpAccount,Long id) throws WxErrorException {

        try{
            String kfAccount  =  "test@"+mpAccount.getAccount();
            wxService.switchoverTo(mpAccount.getAppId()).getKefuService().kfAccountDel(kfAccount);
        }catch (WxErrorException e){
            log.error("WxErrorException occurred while creating tag: {}", e.getError().getErrorCode(), e);
            throw e;
        }catch (Exception e) {
            log.error("Error creating tag: {}", e.getMessage(), e);
            throw new WxErrorException(e);
        }
        return mpKfMapper.deleteMpKfById(id) != 0;
    }
}
